package com.tpv.app.volley.demo.util;

import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class UpLoadFile extends Request<String>
{
    private String file;
    private String url;
    private String contentType = "multipart/form-data";
    private String boundary = "--boundary-2018-12-21-upload-file";
    private VolleyListener mVolleyListener;
    private Bitmap mBitmap;
    
    public UpLoadFile(String url, String file, Bitmap bitmap, VolleyListener listener)
    {
        super(Method.POST, url, listener);
        this.file = file;//上传文件
        this.url = url;
        this.mVolleyListener = listener;
        this.mBitmap = bitmap;
        setRetryPolicy(new DefaultRetryPolicy(5000 * 6, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
    
    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response)
    {
        try
        {
            String parse = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(parse, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e)
        {
            return Response.error(new ParseError(e));
        }
    }
    
    @Override
    protected void deliverResponse(String response)
    {
        mVolleyListener.onResponse(response);
    }
    
    @Override
    public byte[] getBody() throws AuthFailureError
    {
        if (TextUtils.isEmpty(file))
        {
            return super.getBody();
        }
        /*
        * 写入一个图片格式的表单
        *
         ----boundary-2018-12-21-upload-file
         Content-Disposition:form-data;name="image";filename="avatar"
         Content-Type:image/png
        (该行空一行再换行)
        图片的二进制流
        ----boundary-2018-12-21-upload-file--
        *
        *
        * */
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        StringBuilder sb = new StringBuilder();
        //表单第一行
        sb.append("--").append(boundary);
        sb.append("\r\n");
        //表单第二行
        sb.append("Content-Disposition:form-data;");
        sb.append("name=");
        sb.append("\"upload\";filename=");//需要和后台设置的上传名称一致，否则后台会报空指针
        sb.append("\"");
        sb.append(file);
        sb.append("\"");
        sb.append("\r\n");
        //表单第三行
        sb.append("Content-Type:");
        sb.append("image/png");
        sb.append("\r\n");
        //表单第四行
        sb.append("\r\n");
        try
        {
            bos.write(sb.toString().getBytes("UTF-8"));
            //表单第五行 文件写入
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_PICTURES + File.separator + "capture.png");
            System.out.println("文件路径：" + file.getAbsolutePath());
            FileInputStream inputStream = new FileInputStream(file);
            final byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) != -1)
            {
                VolleyLog.e("len --> %s", String.valueOf(len));
                bos.write(buffer, 0, len);
            }
            VolleyLog.e("===last====len --> %s", String.valueOf(len));
            bos.write("\r\n".getBytes("utf-8"));
            sb.append("\r\n");
            String endLine = "--" + boundary + "--" + "\r\n";
            sb.append(endLine);
            bos.write(endLine.getBytes("utf-8"));
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        /*结尾行*/
        //`"--" + BOUNDARY + "--" + "\r\n"`
        System.out.println(sb.toString());
        return bos.toByteArray();
    }
    
    @Override
    public String getBodyContentType()
    {
        return contentType + ";boundary=" + boundary;
    }
}
